package tdd.demo.demo001;

public class TicTacToe {

	private Character[][] board = { 
			{ '\0', '\0', '\0' }, 
			{ '\0', '\0', '\0' }, 
			{ '\0', '\0', '\0' } 
	};

	private char lastPlayer = '\0';

	private static final int SIZE = 3;

	public String play(int x, int y) {
		checkAxis(x);
		checkAxis(y);
		
		lastPlayer = nextPlayer();
		
		setBox(x, y, lastPlayer);
		
		if (isWin(x, y)) {
			return lastPlayer + " is the winner";
		} else if (isDraw()) {
			return "The result is draw";
		} else {
			return "No winner";
		}
	}

	private boolean isDraw() {
		for (int x = 0; x < SIZE; x++) {
			for (int y = 0; y < SIZE; y++) {
				if (board[x][y] == '\0') {
					return false;
				}
			}
		}
		return true;
	}

	private boolean isWin(int x, int y) {
		int playerTotal = lastPlayer * SIZE;
		char horizontal, vertical, diagonal1, diagonal2;
		horizontal = vertical = diagonal1 = diagonal2 = '\0';
		for (int i = 0; i < SIZE; i++) {
			horizontal += board[i][y - 1];
			vertical += board[x - 1][i];
			diagonal1 += board[i][i];
			diagonal2 += board[i][SIZE - i - 1];

		}
		if (horizontal == playerTotal || vertical == playerTotal || diagonal1 == playerTotal
				|| diagonal2 == playerTotal) {
			return true;
		}
		return false;
	}
	/*
	 * x,y是从1开始的，对应数组应该-1作为角标.
	 *	检查放置棋子的位置是否被占用，如果未占用，就将相应数组元素的值从空（\0）改为占用（），注意， 我们还同时记录棋子是谁（X 还是 O）的。
	 */
	private void setBox(int x, int y, char lastPlayer) {
		if (board[x - 1][y - 1] != '\0') {
			throw new RuntimeException("Box is occupied");
		} else {
			board[x - 1][y - 1] = lastPlayer;
		}
	}

	/*
	 * 	下一个落子的人是X还是O
	 */
	public char nextPlayer() {
		if (lastPlayer == 'X') {
			return 'O';
		}
		return 'X';
	}

	private void checkAxis(int axis) {
		if (axis < 1 || axis > 3) {
			throw new RuntimeException("X or Y is outside board");
		}
	}

}
